package com.shunda.ysdgj.manager.service.impl.goods;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.yulichang.base.MPJBaseService;
import com.github.yulichang.base.MPJBaseServiceImpl;
import com.github.yulichang.toolkit.JoinWrappers;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.shunda.ysdgj.common.exception.CustomException;
import com.shunda.ysdgj.manager.mapper.goods.GoodsSkuSpecMapper;
import com.shunda.ysdgj.manager.service.goods.GoodsSkuSpecService;
import com.shunda.ysdgj.model.entity.goods.GoodsSkuSpec;
import com.shunda.ysdgj.model.entity.goods.GoodsSpec;
import com.shunda.ysdgj.model.vo.ResultCodeEnum;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class GoodsSkuSpecServiceImpl
        extends MPJBaseServiceImpl<GoodsSkuSpecMapper, GoodsSkuSpec>
        implements GoodsSkuSpecService, MPJBaseService<GoodsSkuSpec> {

    public List<GoodsSkuSpec> findBySkuId(Long id) {
        MPJLambdaWrapper<GoodsSkuSpec> baseWrapper = JoinWrappers
                .lambda(GoodsSkuSpec.class)
                .select(GoodsSkuSpec::getSkuId, GoodsSkuSpec::getSpecId, GoodsSkuSpec::getSpecItemId)
                .leftJoin(GoodsSpec.class, GoodsSpec::getId, GoodsSkuSpec::getSpecId)
                .eq(GoodsSkuSpec::getSkuId, id)
                .orderByAsc(GoodsSpec::getSpecSort);
        return getBaseMapper().selectJoinList(GoodsSkuSpec.class, baseWrapper);
    }

    @Transactional
    public boolean add(List<GoodsSkuSpec> goodsSkuSpecList) {
        if (!goodsSkuSpecList.isEmpty()) {
            if (!saveBatch(goodsSkuSpecList)) {
                throw new CustomException(ResultCodeEnum.FAIL);
            }
        }
        return true;
    }

    @Transactional
    public boolean modify(Long skuId, List<GoodsSkuSpec> goodsSkuSpecList) {
        if (!goodsSkuSpecList.isEmpty()) {
            LambdaQueryWrapper<GoodsSkuSpec> baseWrapper = new LambdaQueryWrapper<>();
            if (!remove(baseWrapper.eq(GoodsSkuSpec::getSkuId, skuId))) {
                throw new CustomException(ResultCodeEnum.FAIL);
            }
            if (!saveBatch(goodsSkuSpecList)) {
                throw new CustomException(ResultCodeEnum.FAIL);
            }
        }
        return true;
    }

    @Transactional
    public boolean deleteBySkuIds(List<Long> ids) {
        LambdaQueryWrapper<GoodsSkuSpec> baseWrapper = new LambdaQueryWrapper<>();
        if (!remove(baseWrapper.in(GoodsSkuSpec::getSkuId, ids))) {
            throw new CustomException(ResultCodeEnum.FAIL);
        }
        return true;
    }

}
